<template>
  <view class="page">
    <!-- 搜索区 -->
    <view class="search-container">
      <view class="search-wrapper">
        <!-- 添加输入框 -->
        <view class="search-input-wrapper">
          <uni-easyinput
              v-model="billNo"
              placeholder="请输入配送计划号"
              @input="handleInput"
          >
          </uni-easyinput>
        </view>
        <view class="add-btn" @click="handleExit">
          <uni-icons type="closeempty" size="24" color="#FFFFFF"></uni-icons>
        </view>
      </view>
    </view>
    <!-- 列表区域 -->
    <scroll-view
        scroll-y
        class="list-container"
        @scrolltolower="loadMore"
    >
      <view
          v-for="(item, index) in list"
          :key="item.id || index"
          class="order-card"
      >
        <view class="order-header">
          <text class="order-no">{{ item.billNo }}</text>
        </view>
        <view class="info-grid">
          <view class="info-item">
            <uni-icons type="smallcircle" size="18" color="#666"></uni-icons>
            <text class="info-text">{{ item.plateNo }}</text>
            <!--            <view class="vehicle-tag">临</view>-->
          </view>
          <view class="info-item">
            <uni-icons type="contact-filled" size="18" color="#666"></uni-icons>
            <text class="info-text">{{ item.driver }}</text>
          </view>
          <view class="info-item">
            <uni-icons type="location" size="18" color="#666"></uni-icons>
            <text
                class="info-text"
                :class="{ 'text-ellipsis': !showFullText[index] }"
                @click="toggleFullText(index)"
            >
              {{ item.toDeptName || '暂无信息' }}
            </text>
          </view>
          <view class="info-item" v-if="item.remark">
            <uni-icons type="info-filled" size="18" color="#666"></uni-icons>
            <text
                class="info-text"
                :class="{ 'text-ellipsis': !showFullText[index] }"
                @click="toggleFullText(index)"
            >
              {{ item.remark }}
            </text>
          </view>
        </view>
        <view class="time-info">
          <view class="time-item">
            <uni-icons type="calendar" size="18" color="#666"></uni-icons>
            <text class="time-label">出发时间：</text>
            <text class="time-value">{{ item.billDate }}</text>
          </view>
          <view class="time-item">
            <uni-icons type="calendar" size="18" color="#666"></uni-icons>
            <text class="time-label">预计到达：</text>
            <text class="time-value">{{ item.arrviedDate }}</text>
          </view>
        </view>
        <view class="seal-info">
          <uni-collapse>
            <!-- 罐信息 -->
            <view v-if="item.tankInfoList && item.tankInfoList.length > 0">
              <uni-collapse-item>
                <template v-slot:title>
                  <view class="collapse-header">
                    <text class="collapse-title">罐信息</text>
                  </view>
                </template>
                <view class="table-container">
                  <view class="table-header">
                    <text class="table-cell">配送单号</text>
                    <text class="table-cell">加油站罐信息</text>
                    <text class="table-cell">数量(T)</text>
                  </view>
                  <view
                      v-for="(tank, tankIndex) in item.tankInfoList"
                      :key="tankIndex"
                      class="table-row"
                  >
                    <text
                        class="table-cell number-cell"
                        :class="{ 'expanded': tank.showFullBillText }"
                        @click.stop="toggleFullBillText(index, tankIndex)"
                        :style="{ zIndex: tank.showFullBillText ? 2 : 1 }"
                    >
                      <text v-if="tank.showFullBillText">{{ tank.billNo }}</text>
                      <text v-else>{{ formatTruncatedText(tank.billNo) }}</text>
                    </text>
                    <text
                        class="table-cell text-ellipsis-cell"
                        :class="{ 'expanded': tank.showFullTankText }"
                        @click.stop="toggleFullTankText(index, tankIndex)"
                    >
                      {{ tank.toName || '暂无信息' }}
                    </text>
                    <text class="table-cell">{{ tank.numberT }}</text>
                  </view>
                </view>
              </uni-collapse-item>
            </view>
            <!-- 铅封信息 -->
            <view v-if="item.sealInfoList && item.sealInfoList.length > 0">
              <uni-collapse-item>
                <template v-slot:title>
                  <view class="collapse-header">
                    <text class="collapse-title">铅封信息</text>
                  </view>
                </template>
                <view class="table-container">
                  <view class="table-header">
                    <text class="table-cell">铅封编号</text>
                    <text class="table-cell">铅封类型</text>
                    <text class="table-cell">状态</text>
                  </view>
                  <view
                      v-for="(seal, index) in item.sealInfoList"
                      :key="index"
                      class="table-row"
                  >
                    <text
                        class="table-cell number-cell"
                        :class="{ 'expanded': showFullSealText[index] }"
                        @click="toggleFullSealText(index)"
                    >
                      <text v-if="showFullSealText[index]">{{ seal.snCode }}</text>
                      <text v-else>{{ formatTruncatedText(seal.snCode) }}</text>
                    </text>
                    <text
                        class="table-cell text-ellipsis-cell"
                        :class="{ 'expanded': showFullTypeText[index] }"
                        @click="toggleFullTypeText(index)"
                    >
                      {{ seal.snType }}
                    </text>
                    <text class="table-cell">{{ seal.status }}</text>
                  </view>
                </view>
              </uni-collapse-item>
            </view>
          </uni-collapse>
        </view>
      </view>
      <view v-if="!loading && list.length === 0" class="no-data">
        暂无数据
      </view>
      <view v-if="loading" class="loading-text">
        加载中...
      </view>
    </scroll-view>
  </view>
</template>
<script lang="ts" setup>
import {onMounted, ref, watch} from 'vue';
import UniEasyinput from '@dcloudio/uni-ui/lib/uni-easyinput/uni-easyinput.vue';
import UniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
import UniCollapse from '@dcloudio/uni-ui/lib/uni-collapse/uni-collapse.vue';
import UniCollapseItem from '@dcloudio/uni-ui/lib/uni-collapse-item/uni-collapse-item.vue';
import {findTruckBillListByBillNo} from "@/api/function/truckBill/truckBill";

const billNo = ref('');
const loading = ref(false);
const list = ref([]);
const showFullText = ref<boolean[]>([]);
const showFullTankText = ref<boolean[]>([]);
const showFullSealText = ref<boolean[]>([]);
const showFullBillText = ref<boolean[]>([]);
const showFullTypeText = ref<boolean[]>([]);

const getListData = async (billNo = '') => {
  loading.value = true;
  try {
    const response = await findTruckBillListByBillNo(1, 10, billNo);
    if (response.code === 200) {
      list.value = response.rows.map(item => ({
        ...item,
        // 为每个罐信息初始化展开状态
        tankInfoList: item.tankInfoList?.map(tank => ({
          ...tank,
          showFullBillText: false,
          showFullTankText: false
        })) || []
      }));
    } else {
      console.error('查询异常:', response.msg);
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getListData();
});

watch(billNo, {
  handler(newVal) {
    console.log('watch billNo:', newVal);
    if (newVal) {
      getListData(newVal);
    }
  },
  immediate: true
});

// 新增 toggleFullText 方法，用于切换备注的显示状态
const toggleFullText = (index: number) => {
  showFullText.value[index] = !showFullText.value[index];
};
const currentPage = ref(1);
const pageSize = ref(10);
const loadMore = async () => {
  if (loading.value) return;
  loading.value = true;
  currentPage.value++;
  try {
    const response = await findTruckBillListByBillNo(currentPage.value, pageSize.value, billNo.value);
    let newItems = [];
    if (Array.isArray(response)) {
      // 如果返回的直接是数组
      newItems = response;
    } else if (response && response.data && Array.isArray(response.data.rows)) {
      // 如果返回的数据结构是 { data: { rows: [...] } }
      newItems = response.data.rows;
    } else {
      console.error('接口返回数据格式不正确');
    }
    list.value = [...list.value, ...newItems];
    showFullText.value = list.value.map(() => false);
  } catch (error) {
    console.error('加载更多数据失败:', error);
    currentPage.value--;
  } finally {
    loading.value = false;
  }
};
const toggleFullTankText = (itemIndex: number, tankIndex: number) => {
  if (!list.value[itemIndex]?.tankInfoList?.[tankIndex]) return;
  list.value[itemIndex].tankInfoList[tankIndex].showFullTankText =
      !list.value[itemIndex].tankInfoList[tankIndex].showFullTankText;
};
const toggleFullSealText = (index: number) => {
  showFullSealText.value[index] = !showFullSealText.value[index];
};
const toggleFullBillText = (itemIndex: number, tankIndex: number) => {
  if (!list.value[itemIndex]?.tankInfoList?.[tankIndex]) return;
  list.value[itemIndex].tankInfoList[tankIndex].showFullBillText =
      !list.value[itemIndex].tankInfoList[tankIndex].showFullBillText;
};
const toggleFullTypeText = (index: number) => {
  showFullTypeText.value[index] = !showFullTypeText.value[index];
};

const handleInput = (value) => {
  billNo.value = value;
  getListData(value);
};

// 修改格式化方法
const formatTruncatedText = (text: string) => {
  if (!text) return '暂无信息';

  // 设置要显示的后缀长度
  const suffixLength = 8;

  // 如果文本长度小于等于后缀长度，直接返回完整文本
  if (text.length <= suffixLength) return text;

  // 保留后面suffixLength个字符，前面显示省略号
  return `...${text.slice(-suffixLength)}`;
};

// 添加退出方法
const handleExit = () => {
  uni.redirectTo({
    url: '/pages/index',
    success: () => {
      console.log('退出成功，已跳转至首页');
    },
    fail: (error) => {
      console.error('跳转失败:', error);
      // 如果跳转失败，尝试使用 switchTab（如果首页是 tabBar 页面）
      uni.switchTab({
        url: '/pages/index'
      });
    }
  });
};
</script>
<style>
page {
  height: 100%;
}

.page {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.search-container {
  background-color: #ffffff;
  padding: 15rpx 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.search-input-wrapper {
  flex: 1;
  min-width: 100px;
}

.add-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2979ff;
  border-radius: 12rpx;
  margin-top: 0;
  cursor: pointer;
}

.add-btn:active {
  opacity: 0.8;
}

.list-container {
  flex: 1;
  padding: 20rpx 30rpx;
  overflow: hidden; /* 移除滚动 */
  display: flex;
  flex-direction: column;
}

.order-card {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  flex-shrink: 0; /* 防止卡片压缩 */
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-no {
  font-size: 32rpx;
  font-weight: bold;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.info-text {
  font-size: 28rpx;
  color: #666666;
}

.text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 8em;
}

.time-info {
  margin-bottom: 20rpx;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 12rpx;
}

.time-label {
  font-size: 28rpx;
  color: #666666;
  white-space: nowrap;
}

.time-value {
  font-size: 28rpx;
  color: #666666;
}

.seal-info {
  margin-top: 40rpx;
  border-top: 2rpx solid #f0f0f0;
  padding-top: 12rpx;
  position: relative; /* 确保铅封信息位置正确 */
  z-index: 1; /* 防止被覆盖 */
}

.collapse-header {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding-top: 8rpx;
}

.collapse-title {
  font-size: 28rpx;
  color: #999999;
}

.table-container {
  margin-top: 16rpx;
  overflow: visible;
  flex: 1;
  max-height: 400rpx; /* 限制表格高度 */
  overflow-y: auto; /* 添加表格滚动 */
}

.table-header,
.table-row {
  display: grid;
  grid-template-columns: 35% 40% 25%;
  font-size: 28rpx;
  align-items: center;
}

.table-header {
  background-color: #f8f9fa;
  padding: 24rpx 0;
}

.table-cell {
  padding: 0 20rpx;
  box-sizing: border-box;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.loading-text {
  text-align: center;
  padding: 20rpx 0;
  color: #999999;
  font-size: 28rpx;
}

/* 修改编号单元格样式 */
.number-cell {
  cursor: pointer;
  position: relative;
  padding-right: 30rpx;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  min-height: 40rpx; /* 改为 min-height */
  line-height: 1.5; /* 调整行高 */
  display: block;
}

.number-cell.expanded {
  white-space: normal;
  word-break: break-all;
  min-height: auto; /* 展开时取消最小高度限制 */
}

/* 修改文本省略单元格样式 */
.text-ellipsis-cell {
  cursor: pointer;
  position: relative;
  padding-right: 30rpx;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  min-height: 40rpx; /* 改为 min-height */
  line-height: 1.5; /* 调整行高 */
  display: block;
}

.text-ellipsis-cell.expanded {
  white-space: normal;
  word-break: break-all;
  min-height: auto; /* 展开时取消最小高度限制 */
}

/* 修改表格行样式 */
.table-row {
  display: grid;
  grid-template-columns: 35% 40% 25%;
  font-size: 28rpx;
  align-items: flex-start;
  padding: 24rpx 0;
  border-bottom: 2rpx solid #e9e9e9;
  min-height: auto;
}

.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 28rpx;
  color: #999;
}

.uni-collapse-item__wrap {
  max-height: 500rpx !important; /* 设置最大高度 */
  overflow-y: auto !important; /* 添加垂直滚动 */
  transition: max-height 0.3s ease; /* 添加展开动画 */
}
</style>
